package com.hsogoo.collate.redis;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author huangsaigang
 * Created @2019/4/4.
 */
public class RedisClusterConfiguration {

    @Value("${redis.timeout}")
    private Integer timeout;
    @Value("${redis.maxRedirections}")
    private Integer maxRedirections;
    @Value("${redis.cluster.address}")
    private String address;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.maxTotal}")
    private int maxTotal;
    @Value("${redis.minIdle}")
    private int minIdle;
    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.testOnReturn:true}")
    private Boolean testOnReturn;
    @Value("${redis.testOnBorrow:true}")
    private Boolean testOnBorrow;
    @Value("${redis.auth:null}")
    private String auth;

    @Bean
    public JedisCluster jedisCluster(){

        Set<HostAndPort> haps = this.parseHostAndPort();
        GenericObjectPoolConfig genericObjectPoolConfig = createGenericObjectPoolConfig();
        JedisCluster jedisCluster = null;
        if(StringUtils.isNotBlank(auth) && !"null".equals(auth)){
            jedisCluster = new JedisCluster(haps, timeout, timeout, maxRedirections, auth, genericObjectPoolConfig);
        }else{
            jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);
        }
        return jedisCluster;
    }

    @Bean
    public RedisClient redisClient() {
        return new ClusterRedisClient();
    }

    private GenericObjectPoolConfig createGenericObjectPoolConfig() {
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxWaitMillis((long)this.maxWaitMillis);
        genericObjectPoolConfig.setMaxTotal(this.maxTotal);
        genericObjectPoolConfig.setMinIdle(this.minIdle);
        genericObjectPoolConfig.setMaxIdle(this.maxIdle);
        genericObjectPoolConfig.setTestOnBorrow(this.testOnBorrow);
        genericObjectPoolConfig.setTestOnReturn(this.testOnReturn);
        return genericObjectPoolConfig;
    }

    private Set<HostAndPort> parseHostAndPort() {
        Set<HostAndPort> haps = new HashSet();
        String[] address = this.address.split(",");

        for(int i = 0; i < address.length; ++i) {
            String[] ipAndPort = address[i].split(":");
            HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
            haps.add(hap);
        }

        return haps;
    }

}
